<?php
namespace app\admin\model;

use Atlaxy\Model;
use think\facade\Session;

class User extends Model
{
    public function getRoleAttr($val,$data)
    {
        return Role::where('id',$data['role_id'])->find();
    }
    public function login(Array $data)
    {
        $user = $this->where('username',$data['username'])->find();
        if(!$user){
            $this->error = "用户不存在";
            return false;
        }
        if($user->status == 0){
            $this->error = "用户已被禁用";
            return false;
        }
        if($user->password != md5($data['password'])){
            $this->error = "密码错误";
            return false;
        }
        $user->recordLogin();
        Session::set('user',$user);
        return true;
    }

    public function recordLogin()
    {
        
    }

    public function add(Array $data)
    {
        if(!isset($data['username'])){
            $this->error = "用户名不能为空";
            return false;
        }
        if(!isset($data['password'])){
            $this->error = "密码不能为空";
            return false;
        }
        if(!isset($data['role_id'])){
            $this->error = "角色不能为空";
            return false;
        }
        $role = Role::find($data['role_id']);
        if(!$role){
            $this->error = "角色不存在";
            return false;
        }
        $data['password'] = md5($data['password']);
        $user = self::create($data);
        if(!$user){
            $this->error = "添加失败";
            return false;
        }
        return true;
    }

    public function edit(Array $data)
    {
        if(!isset($data['id'])){
            $this->error = "数据有误";
            return false;
        }
        $user = self::find($data['id']);
        if(!$user){
            $this->error = "用户不存在";
            return false;
        }
        if(!isset($data['username'])){
            $this->error = "用户名不能为空";
            return false;
        }
        if(isset($data['password']) && $data['password']){
            $data['password'] = md5($data['password']);
        }else{
            unset($data['password']);
        }
        if(!isset($data['role_id'])){
            $this->error = "角色不能为空";
            return false;
        }
        $role = Role::find($data['role_id']);
        if(!$role){
            $this->error = "角色不存在";
            return false;
        }
        return $user->save($data);
    }
}